package controller

import (
	"GoAdmin/common"
	"GoAdmin/models"
	"GoAdmin/utils"
	"encoding/json"
	"fmt"
	"github.com/astaxie/beego/validation"
	"github.com/gin-gonic/gin"
	"github.com/mozillazg/request"
	"github.com/spf13/cast"
	"io"
	"log"
	"net/http"
	"net/url"
	"strconv"
	"time"
	"xorm.io/builder"
)

func TerminalAdd(c *gin.Context) {
	terminal := new(models.Terminal)
	var (
		err error
	)
	if terminal, _ = new(models.Terminal).GetTerminalByImei(c.PostForm("imei")); terminal.Id > 0 {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "该IMEI已经存在"})
		return
	}
	if err = c.ShouldBind(terminal); err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err.Error()})
		return
	}
	if terminal.InstallDate, err = time.Parse("2006-01-02", c.PostForm("install_date")); err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "安装日期格式错误"})
		return
	}
	if len(terminal.Imei) != 15 {
		fmt.Println(len(terminal.Imei))
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "请输入15位的有效数字"})
		return
	}
	if terminal.Imei != "000000000000000" {
		imer, _ := strconv.Atoi(terminal.Imei)
		if imer == 0 {
			c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "请输入15位的有效数字"})
			return
		}
	}
	terminal.TerminalGroupId = 1
	terminal.Isused = "1"
	terminal.RecordStatus = "0"
	terminal.ApprovalStatus = "1"
	if !terminal.Save() {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "添加计时终端失败"})
		return
	}
	c.JSON(http.StatusOK, gin.H{"code": 200, "msg": "添加终端成功"})
	return
}

func TerminalDelete(c *gin.Context) {
	var (
		terminal *models.Terminal
		err      error
	)
	id := c.PostForm("terminal_id")
	terminal = new(models.Terminal)
	if terminal.Id, err = strconv.ParseInt(id, 10, 64); err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "参数错误"})
		return
	}
	if terminal = new(models.Terminal).GetTerminalById(id); terminal.Id == 0 {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "参数错误"})
		return
	}
	filter := builder.NewCond()
	filter = filter.And(builder.Eq{"ld.terminal_id": terminal.Id})
	filter = filter.And(builder.Gte{"ld.lasting_minute": 1})
	filter = filter.And(builder.Eq{"ld.record_status": "0"})
	if c.PostForm("force") != "1" {
		_, count := new(models.LearnRecord).GetUserLearnRecord(filter)
		if count >= 1 {
			c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "该终端存在未备案关联学时,请备案学时后再删除"})
			return
		}
	}
	var terminalcar models.TerminalCar
	if terminalcar, err = new(models.TerminalCar).GetOneTerminalCarByTerminalId(id); terminalcar.Id > 0 {
		if terminalcar.Reged == "1" {
			c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "该终端已鉴权,请在终端注销后删除"})
			return
		}
	}
	fmt.Println("!!!!!!!!!")
	fmt.Println(terminal)
	if terminal.RecordStatus == "0" {
		if terminal.Isused == "1" {
			terminal.Isused = "0"
			terminal.Hisimei = terminal.Imei
			terminal.Imei = ""
			terminal.InstitutionCode = ""
			if !terminal.Update("isused", "hisimei", "imei", "institution_code") {
				c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "删除终端失败"})
				return
			}
		}
	}
	c.JSON(http.StatusOK, gin.H{"code": 200, "msg": "删除终端成功"})
	return
}

func TerminalInformation(c *gin.Context) {
	var (
		imei     string
		number   string
		schoolId string
	)
	page, _ := strconv.Atoi(c.DefaultPostForm("page", "1"))
	pageSize, _ := strconv.Atoi(c.DefaultPostForm("pageSize", "15"))
	offset := (page - 1) * pageSize
	user, _ := common.GetCtxUser(c)
	filter := builder.NewCond()
	if user.Type == "0" || user.Type == "1" {
		//管理用户查询全部
	} else {
		if user.Province != "" {
			filter = filter.And(builder.Eq{"s.province": user.Province})
		}
		if user.City != "" {
			filter = filter.And(builder.Eq{"s.city": user.City})
		}
		if user.District != "" {
			filter = filter.And(builder.Eq{"s.district": user.District})
		}
	}
	if user.Type == "3" {
		//同一个地区双代理
		filter = filter.And(builder.Eq{"s.config": user.SchoolList})
	}
	if schoolId = c.PostForm("school_id"); schoolId != "" {
		filter = filter.And(builder.Eq{"t.school_id": schoolId})
	}
	if imei = c.PostForm("imei"); imei != "" {
		filter = filter.And(builder.Like{"t.imei", imei})
	}
	if number = c.PostForm("number"); number != "" {
		filter = filter.And(builder.Like{"c.plate_number", number})
	}
	filter = filter.And(builder.Eq{"t.isused": "1"})
	count, list, _ := new(models.Terminal).GetTerminalByFilter(filter, pageSize, offset)
	c.JSON(http.StatusOK, gin.H{"code": 200, "msg": "成功", "data": gin.H{"list": list, "count": count}})
	return
}

func BingDing(c *gin.Context) {
	var (
		schoolId string
	)
	log.Println(c.PostForm("school_id"))
	if schoolId = c.PostForm("school_id"); schoolId == "" {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "查询错误", "data": nil})
		return
	}
	school, _ := new(models.School).GetSchool(schoolId)
	if school.Id <= 0 {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "查询错误", "data": nil})
		return
	}
	reqUrl := `http://127.0.0.1:80/terminal/device/bingding`
	data := url.Values{}
	data.Set("id", c.PostForm("id"))
	data.Set("school_id", cast.ToString(school.Id))
	data.Set("province", school.Province)
	data.Set("city", school.City)
	data.Set("user_id", cast.ToString(school.UserId))
	data.Set("car_number", c.PostForm("car_number"))
	data.Set("sim_number", c.PostForm("sim_number"))
	resp, err := utils.PostForm(reqUrl, data)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err.Error(), "data": nil})
		return
	}
	repMap, _ := cast.ToStringMapE(resp)
	c.JSON(http.StatusOK, gin.H{"code": cast.ToInt(repMap["code"]), "msg": cast.ToString(repMap["msg"]), "data": repMap["data"]})
	return
}

func RemBingDing(c *gin.Context) {
	var (
		ret_map  map[string]interface{}
		car      models.Car
		has      bool
		err      error
		url      string
		req_type int64
	)
	valid := validation.Validation{}
	valid.Required(c.PostForm("id"), "id").Message("记录查询错误")
	valid.Required(c.PostForm("school_id"), "school_id").Message("驾校查询错误")
	valid.Required(c.PostForm("car_number"), "car_number").Message("车辆查询错误")
	valid.Required(c.PostForm("ter_code"), "ter_code").Message("终端编号查询错误")
	valid.Required(c.PostForm("sim"), "sim").Message("Sim查询错误")
	if valid.HasErrors() {
		for _, err := range valid.Errors {
			c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err.Message, "data": nil})
			return
		}
	}
	//查询是否存在绑定车辆
	if has, car, err = new(models.Car).GetCarByNumber(c.PostForm("car_number")); !has {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "车辆不存在"})
		return
	}
	data := map[string]interface{}{
		"devnum": c.PostForm("ter_code"), //终端编号
		"carnum": car.InstitutionCode,    //车辆编号
		"sim":    c.PostForm("sim"),      //终端SIM卡号
	}
	req_type = 2
	school, _ := new(models.School).GetSchool(c.PostForm("school_id"))
	if school.Id <= 0 {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "驾校信息查询错误"})
		return
	}
	//进行解绑
	if url, err = utils.GetSignURL("devRembinding", data, req_type, school.Province, school.City); err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err.Error()})
		return
	}
	client := new(http.Client)
	req := request.NewRequest(client)
	resp, err := req.Post(url)
	defer resp.Body.Close()
	var (
		body []byte
	)
	if body, err = io.ReadAll(resp.Response.Body); err != nil {
		log.Println(err)
	}
	if err = json.Unmarshal(body, &ret_map); err != nil {
		log.Println(err)
	}

	//c.JSON(http.StatusOK, gin.H{"code": cast.ToInt(repMap["code"]), "msg": cast.ToString(repMap["msg"]), "data": repMap["data"]})
	return
}

func DeleteTerminal(c *gin.Context) {
	var (
		schoolId string
	)
	if schoolId = c.PostForm("school_id"); schoolId == "" {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "查询错误", "data": nil})
		return
	}
	school, _ := new(models.School).GetSchool(schoolId)
	if school.Id <= 0 {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "查询错误", "data": nil})
		return
	}
	reqUrl := `http://127.0.0.1:80/terminal/deleteterminal`
	data := url.Values{}
	data.Set("terminal_id", c.PostForm("terminal_id"))
	data.Set("school_id", cast.ToString(school.Id))
	data.Set("province", school.Province)
	data.Set("city", school.City)
	data.Set("user_id", cast.ToString(school.UserId))
	resp, err := utils.PostForm(reqUrl, data)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err.Error(), "data": nil})
		return
	}
	repMap, _ := cast.ToStringMapE(resp)
	c.JSON(http.StatusOK, gin.H{"code": cast.ToInt(repMap["code"]), "msg": cast.ToString(repMap["msg"]), "data": repMap["data"]})
	return
}

func CancelTerminal(c *gin.Context) {

	if c.PostForm("school_id") == "" || c.PostForm("terminal_id") == "" {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "查询错误", "data": nil})
		return
	}
	if !new(models.TerminalCar).CancelTerminal(c.PostForm("terminal_id")) {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "注销失败", "data": nil})
		return
	}
	c.JSON(http.StatusOK, gin.H{"code": 200, "msg": "注销成功", "data": nil})
	return
}

func TerminalUnRecordList(c *gin.Context) {
	var (
		list  []models.CoachRecordList
		count int64
	)
	if c.PostForm("school_id") == "" || c.PostForm("terminal_id") == "" {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "查询错误", "data": nil})
		return
	}
	if c.PostForm("record") == "1" {
		list, count, _ = new(models.LearnRecord).GetTerminalCarRecordList(c.PostForm("terminal_id"))
	} else {
		list, count, _ = new(models.LearnRecord).GetTerminalUnRecordList(c.PostForm("terminal_id"))
	}
	c.JSON(http.StatusOK, gin.H{"code": 200, "msg": "成功", "data": gin.H{"list": list, "count": count}})
	return
}

func TodoRecord(c *gin.Context) {

	if c.PostForm("terminal_id") == "" {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "查询错误", "data": nil})
		return
	}
	if !new(models.LearnRecord).TodoRecord(c.PostForm("terminal_id")) {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "处理失败", "data": nil})
		return
	}
	c.JSON(http.StatusOK, gin.H{"code": 200, "msg": "处理成功", "data": nil})
	return
}
